/*
* Copyright 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
*/
package com.laihuichuxing.producerAndConsumer;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 *
 * @author: Qinxuefeng
 * @since: 1.0
 * Create Date Time: 2018/12/12 14:30
 * Update Date Time:
 */
public  class Producer implements Runnable{
    //定义所有producer共享的计数器，保证在向“产品队列”里放置产品时，产品id唯一
    static class Counter{
        private static int count = 0;
        public static int  increase(){
            return ++count;
        }
    }
    private final int id;
    BlockingQueue<Product> productQueue;
    public Producer(BlockingQueue<Product> productQueue,int id) {
        super();
        this.id = id;
        this.productQueue = productQueue;
    }

    @Override
    public String toString() {
        return "Producer{" +
                "id=" + id +
                '}';
    }

    @Override
    public void run() {
        try {
            while(!Thread.interrupted()){
                TimeUnit.MILLISECONDS.sleep(500);
                synchronized (Counter.class){
                    Product product = new Product(Counter.increase());
                    System.out.println("生产者"+this+"生产出:"+product);
                    productQueue.put(product);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
